﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Tszy.CodeBuilder;
using Tszy.Unlimited.Base;

Console.WriteLine("正在初始化...");
var serviceProvider = Configure();
Console.WriteLine("初始化完成");
Execute(serviceProvider, args);
Console.Read();

#region 初始化

static IServiceProvider? Configure()
{
    try
    {
        return ConfigureServices(new ServiceCollection(), GetConfiguration());
    }
    catch (Exception ex)
    {
        Console.WriteLine($"启动异常");
        Console.WriteLine(ex.Message);
        Console.WriteLine(ex.StackTrace);

        return null;
    }
}

static IConfiguration GetConfiguration()
{
    var settingFile = "appsettings.json";

#if DEBUG
    settingFile = "appsettings.Development.json";
#endif

    var configuration = new ConfigurationBuilder()
        .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
        .AddJsonFile($"Configs/{settingFile}", true, true)
        .Build();

    return configuration;
}

static IServiceProvider ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
    services.RegisterTszyComponent(configuration);
    services.ConfigureServices(configuration);

    return services.BuildServiceProvider();
}

#endregion

static void Execute(IServiceProvider? serviceProvider, string[] args)
{
    if (serviceProvider == null)
        return;

    Tszy.CodeBuilder.Startup.Execute(serviceProvider, args);
}